﻿#define LOGIN

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SiGeSIB.Data.Security;
using System.Data.SqlClient;
using SiGeSIB.GUI.Security;
using SiGeSIB.Services;
using Factories;

namespace SiGeSIB.GUI.Common
{
	public class Manager
	{
		public Manager()
		{
			ServicesProvider = BusinessFactory.CreateServicesProvider();
		}

		#region Attributes
		private static Manager _Instance;
		private FMain _Main;
		private ConfigurationManager _ConfigMgr = ConfigurationManager.Instance;
		#endregion

		#region Properties
		public ConnectionSchema ConnectionSchema { get { return _ConfigMgr.Connections.SelectedSchema; } }
		public string ApplicationDataPath { get { return _ConfigMgr.ApplicationDataPath; } }
		public IServicesProvider ServicesProvider;
		public User LoggedUser { get; set; }
		public static Manager Instance
		{
			get
			{
				if (_Instance == null)
					_Instance = new Manager();
				return _Instance;
			}
		}
		#endregion

		#region Methods
		public void CreateTab(ConflictableForm f)
		{
			_Main.CreateTab(f);
		}
		public void CreateParentTab(UserControl parentControl, ConflictableForm childForm)
		{
			if (parentControl is IRefreshable && childForm is IStateModifier)
			{
				(childForm as IStateModifier).StateModified += new EventHandler<EventArgs<int>>((parentControl as IRefreshable).Reload);
			}

			CreateTab(childForm);
		}
		public SqlConnection CreateConnection()
		{
			return _ConfigMgr.CreateConnection();
		}
		public void InitializeApplication()
		{
#if LOGIN
			FLogin fLogin = new FLogin();
			Application.Run(fLogin);
			if (fLogin.DialogResult == DialogResult.OK)
#endif
				if (_Main == null)
				{
					_Main = new FMain();
					_Main.WindowState = FormWindowState.Maximized;
					_Main.FormClosed += new FormClosedEventHandler(_Main_FormClosed);

					try
					{
						System.Windows.Forms.Application.Run(_Main);
					}
					catch (Exception e)
					{
						FSystemError frm = new FSystemError(e);
						frm.ShowDialog();
					}
				}
		}

		private void _Main_FormClosed(object sender, FormClosedEventArgs e)
		{
			_FinalizeApplication();
		}

		private void _FinalizeApplication()
		{
			_ConfigMgr.SaveConnections();
		}
		#endregion
	}
}
